package com.zzyl.framework.interceptor;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.utils.SecurityUtils;
import lombok.SneakyThrows;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Autowired
    private HttpServletRequest request;


    /**
     *  给小程序端的操作员字段放行。
     * @return
     */
    @SneakyThrows
    public boolean isExclude() {

        try {
            String requestURI = request.getRequestURI();
            if(requestURI.startsWith("/member")) {
                return false;
            }
            return true;
        }catch (Exception e){
            // 如果是定时任务 或者 AMQP消费消息，是没有request的，就会出现异常，针对这种情况，直接选择不填充即可 或者 给默认1 都行
            return false;
        }
    }


    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());

        // /member/login
        if(isExclude()) {
            // 自动填充创建人
            this.strictInsertFill(metaObject, "createBy", String.class, String.valueOf(getLoginUser()));
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", new Date(), metaObject);

        if(isExclude()) {
            // 自动填充修改人
            this.setFieldValByName("updateBy", String.valueOf(getLoginUser()), metaObject);
        }

//        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
//        this.strictUpdateFill(metaObject, "updateBy", String.class, String.valueOf(getLoginUser()));
    }



    public Long getLoginUser() {
        LoginUser loginUser = SecurityUtils.getLoginUser();

        if (loginUser != null) {
            return loginUser.getUserId();
        }
        return 1L;
    }
}
